﻿Imports System.Xml

Namespace Library.Util
    Public Class BuscaCEP
        Implements IDisposable


        Private Const CHAVE As String = "1cRZQkMEMJ3Dp1XilocOHxPJ89yffm1"

        Enum Source As Integer
            BuscarCEP = 1
            Correios = 2
        End Enum

        Private _logradouro As String
        Private _tipoLogradouro As String
        Private _complemento As String
        Private _bairro As String
        Private _municipio As String
        Private _ibgeMunicipio As Integer
        Private _ibgeMunicipioVerificador As Integer
        Private _uf As String
        Private _ibgeUF As Integer
        Private _limite As Integer
        Private _retorno As String

        Public ReadOnly Property Logradouro() As String
            Get
                Return _tipoLogradouro + " " + _logradouro
            End Get
        End Property
        Public ReadOnly Property Bairro() As String
            Get
                Return _bairro
            End Get
        End Property
        Public ReadOnly Property Municipio() As String
            Get
                Return _municipio
            End Get
        End Property
        Public ReadOnly Property IbgeMunicipio() As Integer
            Get
                Return _ibgeMunicipio
            End Get
        End Property
        Public ReadOnly Property IbgeMunicipioVerificador() As Integer
            Get
                Return _ibgeMunicipioVerificador
            End Get
        End Property
        Public ReadOnly Property UF() As String
            Get
                Return _uf
            End Get
        End Property
        Public ReadOnly Property IbgeUF() As Integer
            Get
                Return _ibgeUF
            End Get
        End Property
        Public ReadOnly Property Complemento() As String
            Get
                Return _complemento
            End Get
        End Property
        Public ReadOnly Property Retorno() As String
            Get
                Return _retorno
            End Get
        End Property


        Public Function Buscar(ByVal cep As String) As Boolean
            Dim Result As Boolean
            Result = False

            If cep.Length = 8 Then
                Result = BuscarCEP(cep)
            End If

            Return Result
        End Function


        Private Function BuscarCEP(ByVal cep As String) As Boolean

            Dim Result As Boolean
            Result = False

            Dim UrlSource As String = "http://www.buscarcep.com.br/?cep=" & cep & "&formato=xml&chave=" & CHAVE
            Dim reader As New XmlTextReader(UrlSource)
            Dim strTempName, strTempValue As String

            Try
                reader.MoveToContent()

                Do While reader.Read
                    strTempName = reader.Name
                    If reader.NodeType = XmlNodeType.Element Then
                        reader.Read()
                        strTempValue = reader.Value
                        Select Case strTempName
                            Case "tipo_logradouro"
                                _tipoLogradouro = strTempValue
                            Case "logradouro"
                                _logradouro = strTempValue
                            Case "bairro"
                                _bairro = strTempValue
                            Case "cidade"
                                _municipio = strTempValue
                            Case "ibge_municipio"
                                _ibgeMunicipio = CType(strTempValue, Integer)
                            Case "ibge_municipio_verificador"
                                _ibgeMunicipioVerificador = CType(strTempValue, Integer)
                            Case "ibge_uf"
                                _ibgeUF = CType(strTempValue, Integer)
                            Case "uf"
                                _uf = strTempValue
                            Case "complemento"
                                _complemento = strTempValue
                            Case "limite_buscas"
                                _limite = CType(strTempValue, Integer)
                            Case "resultado"
                                If strTempValue = "1" Then
                                    ' CEP OK
                                    Result = True
                                Else
                                    If strTempValue = "-1" Then
                                        'MsgBox("CEP não encontrado.")
                                        _retorno = "CEP não encontrado."
                                    ElseIf strTempValue = "-2" Then
                                        'MsgBox("Formato de CEP inválido.")
                                        _retorno = "Formato de CEP inválido."
                                    ElseIf strTempValue = "-3" Then
                                        'MsgBox("Busca de CEP congestionada. " & vbCrLf & "Aguarde alguns segundos e tente novamente.")
                                        _retorno = "Busca de CEP congestionada. " & vbCrLf & "Aguarde alguns segundos e tente novamente."
                                    Else
                                        'MsgBox("Erro na busca de CEP.")
                                        _retorno = "Erro na busca de CEP."
                                    End If
                                End If
                        End Select
                    End If
                Loop
            Catch ex As Exception
                Debug.Print(ex.Message)
            End Try

            Return Result
        End Function

        Private disposedValue As Boolean = False        ' To detect redundant calls

        ' IDisposable
        Protected Overridable Sub Dispose(ByVal disposing As Boolean)
            If Not Me.disposedValue Then
                If disposing Then
                    ' TODO: free other state (managed objects).
                End If

                ' TODO: free your own state (unmanaged objects).
                ' TODO: set large fields to null.
            End If
            Me.disposedValue = True
        End Sub

#Region " IDisposable Support "
        ' This code added by Visual Basic to correctly implement the disposable pattern.
        Public Sub Dispose() Implements IDisposable.Dispose
            ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
#End Region

    End Class

End Namespace
